import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Divider } from 'antd';
import { withRouter } from 'umi';
import StandardTable from '@/components/StandardTable';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AntdForm from '@/components/AntdForm';
import AntdFormItem from '@/components/AntdFormItem';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import { allDictList } from '@/utils/constans';
import { queryDict } from '@/utils/common';
import { allDispatchType, renderTableAdSelect, columns, allUrl } from './utils';
import styles from './index.less';

@connect(({ partsOffer, component, loading }) => ({
  partsOfferInfo: partsOffer.partsOfferInfo,
  dictObject: component.dictObject,
  partsOfferDict: component.partsOfferDict,
  loading: loading.effects[allDispatchType.info],
}))
@Form.create()
@withRouter
export default class PartsOfferInfo extends Component {
  constructor(props) {
    super(props);
    const {
      form: { getFieldDecorator },
    } = props;
    this.state = {
      detailId: '',
    };
    this.commonParams = {
      getFieldDecorator,
    };
  }

  columns = [
    {
      title: '配件',
      dataIndex: 'partsId',
      width: 150,
      render: (_, record) => {
        const { id, partsOfferDict, disabled } = this.props;
        console.log('partsOfferDict', partsOfferDict);
        if (!id) {
          return (
            <AntdFormItem
              label=" "
              code={`partsId-${record.id}`}
              initialValue={record.allParentIds}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdSelectRegion
                url={allUrl.partsHierList}
                getFirstValue={true}
                split="/"
                showSplit=" => "
                disabled={disabled}
                onChange={value =>
                  this.handleFieldChange(value[value.length - 1], 'partsId', record.id)
                }
                data={partsOfferDict}
                isRate={true}
              />
            </AntdFormItem>
          );
        }
        return <span title={record.allParentNames}>{record.allParentNames}</span>;
      },
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 80,
      render: text => {
        const { dictObject, id, disabled } = this.props;
        if (!id) {
          return (
            <AdSelect
              value={text}
              disabled={disabled}
              data={dictObject[allDictList.partsUnit]}
              disabled={true}
            />
          );
        }
        return renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.partsUnit,
        });
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 80,
      render: text => {
        const { dictObject, id, disabled } = this.props;
        if (!id) {
          return (
            <AdSelect
              value={text}
              disabled={disabled}
              data={dictObject[allDictList.partsType]}
              disabled={true}
            />
          );
        }
        return renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.partsType,
        });
      },
    },
    {
      title: '品牌',
      dataIndex: 'trademark',
      width: 80,
      render: (text, record) => {
        const { id, disabled } = this.props;
        if (!id) {
          return (
            <AntdInput
              value={text}
              disabled={disabled}
              onChange={value => this.handleFieldChange(value, 'trademark', record.id)}
            />
          );
        }
        return text;
      },
    },
    {
      title: '币种',
      dataIndex: 'currencyType',
      width: 80,
      render: (text, record) => {
        const { dictObject, id, disabled } = this.props;
        if (!id) {
          return (
            <AntdFormItem
              label=" "
              code={`currencyType-${record.id}`}
              initialValue={text}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AdSelect
                disabled={disabled}
                data={dictObject[allDictList.currencyType]}
                payload={{ code: allDictList.currencyType }}
                onChange={value => this.handleFieldChange(value, 'currencyType', record.id)}
              />
            </AntdFormItem>
          );
        }
        return renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.currencyType,
        });
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 80,
      render: (text, record) => {
        const { id, disabled } = this.props;
        if (!id) {
          return (
            <AntdFormItem
              label=" "
              code={`price-${record.id}`}
              initialValue={text ? Number(text).toFixed(2) : undefined}
              {...this.commonParams}
              rules={[{ required: true }]}
            >
              <AntdInput
                mode="money"
                disabled={disabled}
                onChange={value => this.handleFieldChange(value, 'price', record.id)}
              />
            </AntdFormItem>
          );
        }
        return text ? Number(text).toFixed(2) : 0;
      },
    },
    {
      title: '质保(月)',
      dataIndex: 'warranty',
      width: 80,
      render: (text, record) => {
        const { id, disabled } = this.props;
        if (!id) {
          return (
            <AntdInput
              value={text}
              disabled={disabled}
              node="number"
              onChange={value => this.handleFieldChange(value, 'warranty', record.id)}
            />
          );
        }
        return text;
      },
    },
    {
      title: '行驶公里',
      dataIndex: 'drvingKm',
      width: 80,
      render: (text, record) => {
        const { id, disabled } = this.props;
        if (!id) {
          return (
            <AntdInput
              mode="money"
              value={text}
              disabled={disabled}
              onChange={value => this.handleFieldChange(value, 'drvingKm', record.id)}
            />
          );
        }
        return text;
      },
    },
  ];

  componentWillMount() {
    const allDict = [allDictList.currencyType, allDictList.partsType, allDictList.partsUnit];
    queryDict({ props: this.props, allDict });
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.queryPartsOfferDict,
      payload: {
        params: {},
        url: allUrl.partsHierList,
      },
    });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      partsOfferInfo,
      onRef,
    } = this.props;
    onRef && onRef(this);
    if (!id) return;
    this.handleStateChange([{ detailId: id }]);
    const detail = partsOfferInfo[id];
    // if (detail) return;
    this.selectPartsOfferInfo(id);
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { id, partsOfferInfo } = nextProps;
    const { detailId } = nextState;
    if (
      !id &&
      !this.state.detailId &&
      (!detailId || (detailId && detailId === '')) &&
      !partsOfferInfo[this.state.detailId]
    ) {
      this.saveAllValue({
        partsOfferInfo: { [this.state.detailId]: { list: [this.getAddDataObj()] } },
      });
    }
    if (this.props.id !== id) {
      this.handleStateChange([{ detailId: id }]);
      this.selectPartsOfferInfo(id);
    }
  }

  selectPartsOfferInfo = (id, payload) => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.info,
      payload: { id, ...payload },
    });
  };

  getAddDataObj = () => {
    return {
      id: `isNew${Math.ceil(Math.random() * 10000) + 10000}`,
      partsId: '',
      type: '',
      unit: '',
      trademark: '',
      currencyType: '',
      price: '',
      warranty: '',
      drvingKm: '',
    };
  };

  addInfo = () => {
    const { detailId } = this.state;
    let newData = this.getInfoData();
    newData = [this.getAddDataObj(), ...newData];
    this.saveAllValue({ partsOfferInfo: { [detailId]: { list: newData } } });
  };

  getInfoData = () => {
    const { partsOfferInfo } = this.props;
    const { detailId } = this.state;
    let newData = [];
    if (partsOfferInfo[detailId]) {
      const data = partsOfferInfo[detailId].list;
      newData = data.map(item => ({ ...item }));
    }
    return newData;
  };

  getRowByKey(id, newData) {
    const data = this.getInfoData();
    return (newData || data).filter(item => item.id === id)[0];
  }

  handleFieldChange(value, fieldName, id) {
    const { detailId } = this.state;
    const { dispatch } = this.props;
    const newData = this.getInfoData();
    const target = this.getRowByKey(id, newData);
    if (target) {
      target[fieldName] = value;
    }
    if (fieldName === 'partsId') {
      if (value) {
        dispatch({
          type: allDispatchType.partsDetail,
          payload: { id: value },
          callback: data => {
            const { unit, type } = data;
            target.unit = unit;
            target.type = type;
            this.saveAllValue({ partsOfferInfo: { [detailId]: { list: newData } } });
          },
        });
      } else {
        target.unit = '';
        target.type = '';
        this.saveAllValue({ partsOfferInfo: { [detailId]: { list: newData } } });
      }
    } else {
      this.saveAllValue({ partsOfferInfo: { [detailId]: { list: newData } } });
    }
  }

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  render() {
    const { partsOfferInfo, loading, onSelectRow, selectedRows, id, disabled } = this.props;
    const { detailId } = this.state;
    const data = partsOfferInfo[detailId] || {};
    return (
      <div className={styles.customPartsOfferInfo}>
        <AntdForm>
          <StandardTable
            loading={loading}
            data={data}
            columns={this.columns}
            selectedRows={selectedRows}
            disabledRowSelected={disabled || id}
            pagination={false}
            scrollX={900}
            scrollY={200}
            canInput={true}
            onSelectRow={selectedRows => {
              onSelectRow(selectedRows);
            }}
          />
        </AntdForm>
      </div>
    );
  }
}
